<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <div :class="advanced ? null: 'fold'">
          <a-row>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="法人行"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 18, offset: 1}">
                <a-select
                          mode="default"
                          :allowClear="true"
                          style="width: 100%"
                          @change="handleInstChange"
                          v-model="queryParams.instId">
                  <a-select-option v-for="r in instIdData" :key="r.label">{{r.label}}-{{r.value}}</a-select-option>
                </a-select>
<!--                <a-input v-if="!this.user.admin" v-model="queryParams.instId" :value="this.user.instId"
                         readonly="readonly"/>-->
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" v-show="queryParams.instId!=''">
              <a-form-item label="设备编号"
                           :labelCol="{span: 5}"
                           :wrapperCol="{span: 18, offset: 1}">
                <a-input v-model="queryParams.deviceNo"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="queryParams.instId!=''">
            <a-col :md="12" :sm="24">
              <a-form-item label="终端厂商"
                           :labelCol="{span: 5}"
                           :wrapperCol="{span: 18, offset: 1}">
                <a-select
                  show-search
                  placeholder="请输入代码或名称"
                  option-filter-prop="children"
                  style="width: 100%"
                  :allowClear="true"
                  :filter-option="filterOption"
                  @search="selectBrandCode"
                  @focus="selectBrandCode"
                  v-model="queryParams.brandCode"
                >
                  <a-select-option v-for="(d,index) in brandCodeData" :key="d.id">
                    {{ d.id }}-{{ d.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="终端型号"
                           :labelCol="{span: 5}"
                           :wrapperCol="{span: 18, offset: 1}">
                <a-select
                  show-search
                  placeholder="请输入代码或名称"
                  option-filter-prop="children"
                  style="width: 100%"
                  :allowClear="true"
                  :filter-option="filterOption"
                  @focus="selectByBrandCode"
                  @search="selectByBrandCode"
                  v-model="queryParams.modelCode"
                >
                  <a-select-option v-for="(d,index) in modelCodeData" :key="d.id">
                    {{ d.id }}-{{ d.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div style="text-align: center;margin-bottom: 20px " v-show="queryParams.instId!=''">
          <a-button type="primary" @click="search">查询</a-button>
          <a-button style="margin-left: 8px" @click="reset">重置</a-button>
        </div>
      </a-form>
    </div>
    <div v-show="queryParams.instId!=''">
      <div class="operator">
        <a-button v-hasPermission="['deviceInfo:add']" ghost type="primary" @click="add">新增</a-button>
        <a-button v-hasPermission="['deviceInfo:import']" ghost type="primary" @click="upload">导入</a-button>
        <a-button v-hasPermission="['deviceInfo:equout']" ghost type="primary" @click="equout">装机出库</a-button>
        <a-button v-hasPermission="['deviceInfo:orgin']" ghost type="primary" @click="orgin">返还入库</a-button>
        <a-button v-hasPermission="['deviceInfo:warning']" ghost type="primary" @click="baoz">报障</a-button>
        <a-button v-hasPermission="['deviceInfo:repout']" ghost type="primary" @click="repout">维修出库</a-button>
        <a-button v-hasPermission="['deviceInfo:repin']" ghost type="primary" @click="repin">修复入库</a-button>
        <a-button v-hasPermission="['deviceInfo:cheji']" ghost type="primary" @click="cheji">撤机</a-button>
        <a-button v-hasPermission="['deviceInfo:chejiin']" ghost type="primary" @click="chejiin">撤机入库</a-button>
        <a-button v-hasPermission="['deviceInfo:sunhui']" ghost type="primary" @click="sunhui">损毁</a-button>
        <a-button v-hasPermission="['deviceInfo:loss']" ghost type="primary" @click="lose">丢失</a-button>
        <a-button v-hasPermission="['deviceInfo:give']" ghost type="primary" @click="give">返还第三方</a-button>



      </div>
      <!-- 表格区域 -->
      <a-table ref="TableInfo"
               :columns="columns"
               :rowKey="record => record.id"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               :scroll="{ x: 4200 }"
               @change="handleTableChange">
        <template slot="email" slot-scope="text, record">
          <a-popover placement="topLeft">
            <template slot="content">
              <div>{{text}}</div>
            </template>
            <p style="width: 150px;margin-bottom: 0">{{text}}</p>
          </a-popover>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-icon v-hasPermission="['deviceInfo:edit']" type="setting" theme="twoTone" twoToneColor="#4a9ff5" @click="editInfo(record)" title="修改"></a-icon>&nbsp;
          <a-icon v-hasPermission="['deviceInfo:view']" type="eye" theme="twoTone" twoToneColor="#42b983" @click="viewInfo(record)" title="查看"></a-icon>
          <a-badge v-hasNoPermission="['deviceInfo:edit','deviceInfo:view']" userStatus="warning" text="无权限"></a-badge>
        </template>

      </a-table>
      <!-- 信息查看 -->
      <device-info-info
        ref="deviceInfoInfo"
        @close="handleDeviceInfoInfoClose"
        :deviceInfoInfoVisiable="deviceInfoInfo.visiable">
      </device-info-info>
      <!-- 新增信息 -->
      <device-info-add
        @close="handleDeviceInfoAddClose"
        @success="handleDeviceInfoAddSuccess"
        :deviceInfoAddVisiable="deviceInfoAdd.visiable"
        :instId="this.queryParams.instId">
      </device-info-add>

      <!-- 信息导入 -->
      <device-info-import
        @close="handleDeviceInfoImportClose"
        :deviceInfoUploadVisiable="deviceInfoUpload.visiable"
        :instId="this.queryParams.instId">
      </device-info-import>

      <!-- 修改信息 -->
      <device-info-edit
        ref="deviceInfoEdit"
        @close="handleDeviceInfoEditClose"
        @success="handleDeviceInfoEditSuccess"
        :deviceInfoEditVisiable="deviceInfoEdit.visiable"
        :instId="this.queryParams.instId">
      </device-info-edit>
    </div>
  </a-card>
</template>

<script>
  import RangeDate from '@/components/datetime/RangeDate';
  import DeviceInfoAdd from "./DeviceInfoAdd";
  import DeviceInfoEdit from "./DeviceInfoEdit";
  import DeviceInfoInfo from "./DeviceInfoInfo";
  import DeviceInfoImport from "./DeviceInfoImport";

  import {mapState} from "vuex"

  export default {
    name: "deviceInfo",
    components: {RangeDate, DeviceInfoAdd, DeviceInfoEdit, DeviceInfoInfo, DeviceInfoImport},
    data() {
      return {
        advanced: false,
        deviceInfoInfo: {
          visiable: false,
          data: {}
        },
        deviceInfoAdd: {
          visiable: false
        },
        deviceInfoUpload: {
          visiable: false
        },
        deviceInfoEdit: {
          visiable: false
        },

        queryParams: {
          deviceNo: '',
          brandCode: '',
          modelCode: '',
          instId: ''
        },
        brandCodeData: [],
        modelCodeData: [],

        dataSource: [],
        sortedInfo: null,
        paginationInfo: null,
        selectedRowKeys: [],
        pagination: {
          pageSizeOptions: ['10', '20', '30', '40', '100'],
          defaultCurrent: 1,
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
        },
        loading: false,
        instIdData: [],
        da: []
      }
    },
    computed: {
      ...mapState({
        user: state => state.account.user,

      }),
      columns() {
        let {sortedInfo} = this
        sortedInfo = sortedInfo || {}
        let {filteredInfo} = this
        filteredInfo = filteredInfo || {}
        return [{
          title: '设备编号',
          dataIndex: 'deviceNo',
          scopedSlots: {customRender: 'deviceNo'},
        }, {
          title: '设备类型',
          dataIndex: 'deviceType',
          customRender: (text, row, index) => {
            switch (text) {
              case '1':
                return <a-tag color = "pink" > 终端机具 < /a-tag>
              case '2':
                return <a-tag color = "pink" > 终端部件 < /a-tag>
              default:
                return text
            }
          },
          filters: [
            {text: '终端机具', value: '1'},
            {text: '终端部件', value: '2'},
          ],
          filterMultiple: false,
          filteredValue: filteredInfo.deviceType || null,
          onFilter: (value, record) => record.deviceType.includes(value)
        }, {
          title: '设备描述',
          dataIndex: 'deviceDesc',
          scopedSlots: {customRender: 'deviceDesc'},
        }, {
          title: '入库方式',
          dataIndex: 'libraryType',
          customRender: (text, row, index) => {
            switch (text) {
              case '01':
                return <a-tag color = "pink" > 手动 < /a-tag>
              case '02':
                return <a-tag color = "pink" > 批量 < /a-tag>
              default:
                return text
            }
          },
          filters: [
            {text: '手动', value: '01'},
            {text: '批量', value: '02'},
          ],
          filterMultiple: false,
          filteredValue: filteredInfo.libraryType || null,
          onFilter: (value, record) => record.libraryType.includes(value)
        }, {
          title: '入库批次号',
          dataIndex: 'libraryBatch',
          scopedSlots: {customRender: 'libraryBatch'},
        }, {
          title: '终端厂商',
          dataIndex: 'brandName',
          scopedSlots: {customRender: 'brandName'},
        }, {
          title: '终端型号',
          dataIndex: 'modelName',
          scopedSlots: {customRender: 'modelName'},
        }, {
          title: 'S/N号',
          dataIndex: 'sn',
          scopedSlots: {customRender: 'sn'},
        }, {
          title: '有效期开始日期',
          dataIndex: 'startDate',
          scopedSlots: {customRender: 'startDate'},
        }, {
          title: '有效期截止日期',
          dataIndex: 'endDate',
          scopedSlots: {customRender: 'endDate'},
        }, {
          title: '设备购置方式',
          dataIndex: 'devicePurchType',
          customRender: (text, row, index) => {
            switch (text) {
              case '00':
                return <a-tag color = "pink" > 自有 < /a-tag>
              case '01':
                return <a-tag color = "pink" > 租用 < /a-tag>
              case '02':
                return <a-tag color = "pink" > 第三方所有 < /a-tag>
              default:
                return text
            }
          },
          filters: [
            {text: '自有', value: '00'},
            {text: '租用', value: '01'},
            {text: '第三方所有', value: '02'},
          ],
          filterMultiple: false,
          filteredValue: filteredInfo.devicePurchType || null,
          onFilter: (value, record) => record.devicePurchType.includes(value)
        }, {
          title: '设备单价(元)',
          dataIndex: 'devicePrice',
          scopedSlots: {customRender: 'devicePrice'},
        }, {
          title: '设备状态',
          dataIndex: 'status',
          customRender: (text, row, index) => {
            switch (text) {
              case '10':
                return <a-tag color = "pink" > 未使用 < /a-tag>
              case '11':
                return <a-tag color = "pink" > 已使用 < /a-tag>
              case '12':
                return <a-tag color = "pink" > 损毁 < /a-tag>
              case '13':
                return <a-tag color = "pink" > 故障 < /a-tag>
              case '14':
                return <a-tag color = "pink" > 装机出库 < /a-tag>
              case '15':
                return <a-tag color = "pink" > 撤机 < /a-tag>
              case '16':
                return <a-tag color = "pink" > 丢失 < /a-tag>
              case '17':
                return <a-tag color = "pink" > 返回第三方 < /a-tag>
              default:
                return text
            }
          },
          filters: [
            {text: '未使用', value: '10'},
            {text: '已使用', value: '11'},
            {text: '损毁', value: '12'},
            {text: '故障', value: '13'},
            {text: '装机出库', value: '14'},
            {text: '撤机', value: '15'},
            {text: '丢失', value: '16'},
            {text: '返回第三方', value: '17'},
          ],
          filterMultiple: false,
          filteredValue: filteredInfo.status || null,
          onFilter: (value, record) => record.status.includes(value)
        }, {
          title: '审核状态',
          dataIndex: 'auditStatus',
          customRender: (text, row, index) => {
            switch (text) {
              case '00':
                return <a-tag color = "cyan" > 待提交审批 < /a-tag>
              case '01':
                return <a-tag color = "pink" > 新增-审批流程中 < /a-tag>
              case '02':
                return <a-tag color = "pink" > 新增-审批通过 < /a-tag>
              case '03':
                return <a-tag color = "pink" > 新增-审批拒绝 < /a-tag>
              case '11':
                return <a-tag color = "cyan" > 注销-审批流程中 < /a-tag>
              case '12':
                return <a-tag color = "pink" > 注销-审批通过 < /a-tag>
              case '13':
                return <a-tag color = "pink" > 注销-审批拒绝 < /a-tag>
              case '21':
                return <a-tag color = "pink" > 停用-审批流程中 < /a-tag>
              case '22':
                return <a-tag color = "cyan" > 停用-审批通过 < /a-tag>
              case '23':
                return <a-tag color = "pink" > 停用-审批拒绝 < /a-tag>
              case '31':
                return <a-tag color = "pink" > 启用-审批流程中 < /a-tag>
              case '32':
                return <a-tag color = "pink" > 启用-审批通过 < /a-tag>
              case '33':
                return <a-tag color = "cyan" > 启用-审批拒绝 < /a-tag>
              case '41':
                return <a-tag color = "pink" > 修改-审批流程中 < /a-tag>
              case '42':
                return <a-tag color = "pink" > 修改-审批通过 < /a-tag>
              case '43':
                return <a-tag color = "pink" > 修改-审批拒绝 < /a-tag>
              default:
                return text
            }
          },
          filters: [
            {text: '待提交审批', value: '00'},
            {text: '新增-审批流程中', value: '01'},
            {text: '新增-审批通过', value: '02'},
            {text: '新增-审批拒绝', value: '03'},
            {text: '注销-审批流程中', value: '11'},
            {text: '注销-审批通过', value: '12'},
            {text: '注销-审批拒绝', value: '13'},
            {text: '停用-审批流程中', value: '21'},
            {text: '停用-审批通过', value: '22'},
            {text: '停用-审批拒绝', value: '23'},
            {text: '启用-审批流程中', value: '31'},
            {text: '启用-审批通过', value: '32'},
            {text: '启用-审批拒绝', value: '33'},
            {text: '修改-审批流程中', value: '41'},
            {text: '修改-审批通过', value: '42'},
            {text: '修改-审批拒绝', value: '43'}
          ],
          filterMultiple: false,
          filteredValue: filteredInfo.auditStatus || null,
          onFilter: (value, record) => record.auditStatus.includes(value)
        }, {
          title: '关联商户编码',
          dataIndex: 'mchntNo',
          scopedSlots: {customRender: 'mchntNo'},
        }, {
          title: '关联虚拟终端编号',
          dataIndex: 'termNo',
          scopedSlots: {customRender: 'termNo'},
        }, {
          title: '租赁起始日期',
          dataIndex: 'leaseStartDate',
          scopedSlots: {customRender: 'leaseStartDate'},
        }, {
          title: '租赁截止日期',
          dataIndex: 'leaseEndDate',
          scopedSlots: {customRender: 'leaseEndDate'},
        }, {
          title: '租赁费用(元/日)',
          dataIndex: 'deviceLeasePrice',
          scopedSlots: {customRender: 'deviceLeasePrice'},
        }, {
          title: '押金(元）',
          dataIndex: 'cashPledge',
          scopedSlots: {customRender: 'cashPledge'},
        }, {
          title: '法人行',
          dataIndex: 'instId',
          scopedSlots: {customRender: 'instId'},
        }, {
          title: '操作',
          dataIndex: 'operation',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }]
      }
    },
    mounted() {
      this.$get('admin/upmporg/getInstList').then((r) => {
        this.instIdData = r.data
      })
    },
    methods: {
      selectBrandCode(val) {
        if(this.queryParams.instId) {
          this.brandCodeData = []
          let param = {}
          if (val) {
            param = {
              q: encodeURIComponent(val + `&${this.queryParams.instId}`),
              pageSize: 20
            }
          } else {
            param = {
              q: encodeURIComponent(`&${this.queryParams.instId}`),
              pageSize: 20
            }
          }
          this.$get('terminalAdmin/termbrandSelect2List', param).then((r) => {
            let result = r.data.results
            result.forEach(r => {
              this.brandCodeData.push(r);
            })
          })
        } else {
          this.$message.warning('请先选择法人行')
        }

      },

      selectByBrandCode(val) {
        this.modelCodeData = []
        let brandCode = this.queryParams.brandCode
        if (brandCode) {
          let param = {}
          if (val) {
            param = {
              q: encodeURIComponent(val + `&${brandCode}` + `&${this.queryParams.instId}`),
              pageSize: 20
            }
          } else {
            param = {
              q: encodeURIComponent(`&${brandCode}` + `&${this.queryParams.instId}`),
              pageSize: 20
            }
          }

          this.$get('modelAdmin/termmodelSelect2List', param).then((r) => {
            let result = r.data.results
            result.forEach(r => {
              this.modelCodeData.push(r);
            })
          })
        }else {
          this.$message.warning('请先选择终端产商')
        }
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },


      onSelectChange(selectedRowKeys) {  //接收数组，存放到前面定义的数组中
        this.selectedRowKeys = selectedRowKeys;
      },

      add() {
        this.deviceInfoAdd.visiable = true
      },

      upload() {
        this.deviceInfoUpload.visiable = true
      },

      //查数据
      handleInstChange(value) {
        this.queryParams.instId = value;
        if (value != "") {
          let params = {}
          params.instId = value;
          this.$get('deviceInfo',{...params}).then((r) => {
            // console.log(r.data.rows)
            this.dataSource = r.data.rows;
            this.search()
          })
        }
      },

      handleDeviceInfoAddClose() {
        this.deviceInfoAdd.visiable = false
      },
      handleDeviceInfoAddSuccess() {
        this.deviceInfoAdd.visiable = false
        this.$message.success('新增成功')
        this.search()
      },

      handleDeviceInfoImportClose() {
        this.deviceInfoUpload.visiable = false
        this.search()
      },
      equout(){
        let ids = this.selectedRowKeys
        let result = false
        if (ids.length === 0) {
          this.$message.warning("请选择一条数据")
          return;
        } else {
          let selectedDataSource = []
          this.selectedRowKeys.forEach((val,index)=>{
            let id = val
            let selectedIndex = ''
            this.dataSource.map((val, index)=>{
              if(val.id === id) return selectedIndex = index
            })
            selectedDataSource[index] = this.dataSource[selectedIndex]
          })

          selectedDataSource.forEach((val,index)=>{
            console.log(val)
            if (val.status !== '11'){
              this.$message.warning(val.deviceNo + "设备不是已使用状态不能装机出库!")
            } else if (val.mchntNo === '' || val.mchntNo === null){
              this.$message.warning(val.mchntNo + "设备关联商户编码不能为空!")
            } else if (val.termNo === '' || val.termNo === null){
              this.$message.warning(val.termNo + "设备关联虚拟终端编号不能为空!")
            } else if(val.auditStatus === '01' || val.auditStatus === '11' || val.auditStatus === '21'
              || val.auditStatus === '31' || val.auditStatus === '41') {
              this.$message.warning('申请待审批的数据不允许装机出库')
            } else {
              result = true
            }
          })
        }
        if (result) {
          var param = {};
          param.ids = ids.toString();
          param.instId = this.queryParams.instId;
          param.optFlag = "equout";

          this.$put('deviceInfo', param).then((r) => {
            this.selectedRowKeys = []
            this.search()
            this.$message.success('设备装机出库成功！')
          }).catch(() => {
            this.loading = false
          })
        }
      },
      orgin(){
        let ids = this.selectedRowKeys
        let result = false
        if (ids.length === 0) {
          this.$message.warning("请选择一条数据")
          return;
        } else {
          let selectedDataSource = []
          this.selectedRowKeys.forEach((val,index)=>{
            let id = val
            let selectedIndex = ''
            this.dataSource.map((val, index)=>{
              if(val.id === id) return selectedIndex = index
            })
            selectedDataSource[index] = this.dataSource[selectedIndex]
          })

          selectedDataSource.forEach((val,index)=>{
            if (val.status !== '14'){
              this.$message.warning(val.deviceNo + "设备不是装机出库，请选择其他入库状态!")
            } else if (val.auditStatus === '01' || val.auditStatus === '11' || val.auditStatus === '21'
              || val.auditStatus === '31' || val.auditStatus === '41') {
              this.$message.warning('申请待审批的数据不允许返还入库')
            } else {
              result = true
            }
          })
        }
        if (result) {
          var param = {};
          param.ids = ids.toString();
          param.instId = this.queryParams.instId;
          param.optFlag = "orgin";

          this.$put('deviceInfo', param).then((r) => {
            this.selectedRowKeys = []
            this.search()
            this.$message.success('设备返还入库！')
          }).catch(() => {
            this.loading = false
          })
        }
      },
      baoz(){
        let ids = this.selectedRowKeys
        let result = false
        if (ids.length === 0) {
          this.$message.warning("请选择一条数据")
          return;
        } else {
          let selectedDataSource = []
          this.selectedRowKeys.forEach((val,index)=>{
            let id = val
            let selectedIndex = ''
            this.dataSource.map((val, index)=>{
              if(val.id === id) return selectedIndex = index
            })
            selectedDataSource[index] = this.dataSource[selectedIndex]
          })

          selectedDataSource.forEach((val,index)=>{
            if (val.status === '13'){
              this.$message.warning(val.deviceNo + "设备已报障!")
            } else if (val.status === '16'){
              this.$message.warning(val.deviceNo + "设备已丢失，不能保障！")
            } else if (val.auditStatus === '01' || val.auditStatus === '11' || val.auditStatus === '21'
              || val.auditStatus === '31' || val.auditStatus === '41') {
              this.$message.warning('申请待审批的数据不允许报障')
            } else {
              result = true
            }
          })
        }
        if (result) {
          var param = {};
          param.ids = ids.toString();
          param.instId = this.queryParams.instId;
          param.optFlag = "warning";

          this.$put('deviceInfo', param).then((r) => {
            this.selectedRowKeys = []
            this.search()
            this.$message.success('设备报障成功！')
          }).catch(() => {
            this.loading = false
          })
        }
      },
      repout(){
        let ids = this.selectedRowKeys
        let result = false
        if (ids.length === 0) {
          this.$message.warning("请选择一条数据")
          return;
        } else {
          let selectedDataSource = []
          this.selectedRowKeys.forEach((val,index)=>{
            let id = val
            let selectedIndex = ''
            this.dataSource.map((val, index)=>{
              if(val.id === id) return selectedIndex = index
            })
            selectedDataSource[index] = this.dataSource[selectedIndex]
          })

          selectedDataSource.forEach((val,index)=>{
            if (val.status !== '13'){
              this.$message.warning(val.deviceNo + "设备没有报障，不支持维修出库！")
            } else if (val.auditStatus === '01' || val.auditStatus === '11' || val.auditStatus === '21'
              || val.auditStatus === '31' || val.auditStatus === '41') {
              this.$message.warning('申请待审批的数据不允许维修出库')
            } else {
              result = true
            }
          })
        }
        if (result) {
          var param = {};
          param.ids = ids.toString();
          param.instId = this.queryParams.instId;
          param.optFlag = "repout";

          this.$put('deviceInfo', param).then((r) => {
            this.selectedRowKeys = []
            this.search()
            this.$message.success('设备装机出库成功！')
          }).catch(() => {
            this.loading = false
          })
        }
      },
      repin(){
        let ids = this.selectedRowKeys
        let result = false
        if (ids.length === 0) {
          this.$message.warning("请选择一条数据")
          return;
        } else {
          let selectedDataSource = []
          this.selectedRowKeys.forEach((val,index)=>{
            let id = val
            let selectedIndex = ''
            this.dataSource.map((val, index)=>{
              if(val.id === id) return selectedIndex = index
            })
            selectedDataSource[index] = this.dataSource[selectedIndex]
          })

          selectedDataSource.forEach((val,index)=>{
            if (val.status !== '13'){
              this.$message.warning(val.deviceNo + "设备没有故障状态，不允许修复入库!")
            } else if (val.auditStatus === '01' || val.auditStatus === '11' || val.auditStatus === '21'
              || val.auditStatus === '31' || val.auditStatus === '41') {
              this.$message.warning('申请待审批的数据不允许修复入库')
            } else {
              result = true
            }
          })
        }
        if (result) {
          var param = {};
          param.ids = ids.toString();
          param.instId = this.queryParams.instId;
          param.optFlag = "repin";

          this.$put('deviceInfo', param).then((r) => {
            this.selectedRowKeys = []
            this.search()
            this.$message.success('设备修复入库！')
          }).catch(() => {
            this.loading = false
          })
        }
      },
      cheji(){
        let ids = this.selectedRowKeys
        let result = false
        if (ids.length === 0) {
          this.$message.warning("请选择一条数据")
          return;
        } else {
          let selectedDataSource = []
          this.selectedRowKeys.forEach((val,index)=>{
            let id = val
            let selectedIndex = ''
            this.dataSource.map((val, index)=>{
              if(val.id === id) return selectedIndex = index
            })
            selectedDataSource[index] = this.dataSource[selectedIndex]
          })

          selectedDataSource.forEach((val,index)=>{
            if (val.status !== '11'){
              this.$message.warning(val.deviceNo + "该设备状态不支持撤机!")
            } else if (val.auditStatus === '01' || val.auditStatus === '11' || val.auditStatus === '21'
              || val.auditStatus === '31' || val.auditStatus === '41') {
              this.$message.warning('申请待审批的数据不允许撤机')
            } else {
              result = true
            }
          })
        }
        if (result) {
          var param = {};
          param.ids = ids.toString();
          param.instId = this.queryParams.instId;
          param.optFlag = "cheji";

          this.$put('deviceInfo', param).then((r) => {
            this.selectedRowKeys = []
            this.search()
            this.$message.success('设备撤机成功！')
          }).catch(() => {
            this.loading = false
          })
        }
      },
      chejiin(){
        let ids = this.selectedRowKeys
        let result = false
        if (ids.length === 0) {
          this.$message.warning("请选择一条数据")
          return;
        } else {
          let selectedDataSource = []
          this.selectedRowKeys.forEach((val,index)=>{
            let id = val
            let selectedIndex = ''
            this.dataSource.map((val, index)=>{
              if(val.id === id) return selectedIndex = index
            })
            selectedDataSource[index] = this.dataSource[selectedIndex]
          })

          selectedDataSource.forEach((val,index)=>{
            if (val.status !== '15'){
              this.$message.warning(val.deviceNo + "设备不是撤机状态!")
            } else if (val.auditStatus === '01' || val.auditStatus === '11' || val.auditStatus === '21'
              || val.auditStatus === '31' || val.auditStatus === '41') {
              this.$message.warning('申请待审批的数据不允许撤机入库')
            } else {
              result = true
            }
          })
        }
        if (result) {
          var param = {};
          param.ids = ids.toString();
          param.instId = this.queryParams.instId;
          param.optFlag = "chejiin";

          this.$put('deviceInfo', param).then((r) => {
            this.selectedRowKeys = []
            this.search()
            this.$message.success('设备撤机入库！')
          }).catch(() => {
            this.loading = false
          })
        }
      },
      sunhui(){
        let ids = this.selectedRowKeys
        let result = false
        if (ids.length === 0) {
          this.$message.warning("请选择一条数据")
          return;
        } else {
          let selectedDataSource = []
          this.selectedRowKeys.forEach((val,index)=>{
            let id = val
            let selectedIndex = ''
            this.dataSource.map((val, index)=>{
              if(val.id === id) return selectedIndex = index
            })
            selectedDataSource[index] = this.dataSource[selectedIndex]
          })

          selectedDataSource.forEach((val,index)=>{
            if (val.status === '12'){
              this.$message.warning(val.deviceNo + "设备已损毁!")
            } else if (val.status === '16'){
              this.$message.warning(val.deviceNo + "设备已丢失!")
            } else if (val.auditStatus === '01' || val.auditStatus === '11' || val.auditStatus === '21'
              || val.auditStatus === '31' || val.auditStatus === '41') {
              this.$message.warning('申请待审批的数据不允许损毁')
            } else {
              result = true
            }
          })
        }
        if (result) {
          var param = {};
          param.ids = ids.toString();
          param.instId = this.queryParams.instId;
          param.optFlag = "sunhui";

          this.$put('deviceInfo', param).then((r) => {
            this.selectedRowKeys = []
            this.search()
            this.$message.success('设备损毁成功！')
          }).catch(() => {
            this.loading = false
          })
        }
      },
      lose(){
        let ids = this.selectedRowKeys
        let result = false
        if (ids.length === 0) {
          this.$message.warning("请选择一条数据")
          return;
        } else {
          let selectedDataSource = []
          this.selectedRowKeys.forEach((val,index)=>{
            let id = val
            let selectedIndex = ''
            this.dataSource.map((val, index)=>{
              if(val.id === id) return selectedIndex = index
            })
            selectedDataSource[index] = this.dataSource[selectedIndex]
          })

          selectedDataSource.forEach((val,index)=>{
            if (val.status === '16'){
              this.$message.warning(val.deviceNo + "设备已丢失!")
            } else if (val.auditStatus === '01' || val.auditStatus === '11' || val.auditStatus === '21'
              || val.auditStatus === '31' || val.auditStatus === '41') {
              this.$message.warning('申请待审批的数据不允许丢失')
            } else {
              result = true
            }
          })
        }
        if (result) {
          var param = {};
          param.ids = ids.toString();
          param.instId = this.queryParams.instId;
          param.optFlag = "loss";
          this.$put('deviceInfo', param).then((r) => {
            this.selectedRowKeys = []
            this.search()
            this.$message.success('设备丢失！')
          }).catch(() => {
            this.loading = false
          })
        }
      },
      give(){
        let ids = this.selectedRowKeys
        let result = false
        if (ids.length === 0) {
          this.$message.warning("请选择一条数据")
          return;
        } else {
          let selectedDataSource = []
          this.selectedRowKeys.forEach((val,index)=>{
            let id = val
            let selectedIndex = ''
            this.dataSource.map((val, index)=>{
              if(val.id === id) return selectedIndex = index
            })
            selectedDataSource[index] = this.dataSource[selectedIndex]
          })

          selectedDataSource.forEach((val,index)=>{
            if (val.status === '17'){
              this.$message.warning(val.deviceNo + "设备已返还第三方!")
            } else if (val.status === '16'){
              this.$message.warning(val.mchntNo + "设备已丢失，无法返回第三方!")
            } else if (val.auditStatus === '01' || val.auditStatus === '11' || val.auditStatus === '21'
              || val.auditStatus === '31' || val.auditStatus === '41') {
              this.$message.warning('申请待审批的数据不允许返还第三方')
            } else {
              result = true
            }
          })
        }
        if (result) {
          var param = {};
          param.ids = ids.toString();
          param.instId = this.queryParams.instId;
          param.optFlag = "give";

          this.$put('deviceInfo', param).then((r) => {
            this.selectedRowKeys = []
            this.search()
            this.$message.success('设备返还第三方成功！')
          }).catch(() => {
            this.loading = false
          })
        }
      },


      viewInfo(record) {
        record.brandCode = record.brandCode + '-' + record.brandName
        record.modelCode = record.modelCode + '-' + record.modelName

        let effectiveDate = []
        effectiveDate[0]=record.startDate
        effectiveDate[1]=record.endDate
        record.effectiveDate = effectiveDate
        let leaseDate = []
        leaseDate[0]=record.leaseStartDate
        leaseDate[1]=record.leaseEndDate
        record.leaseDate = leaseDate
        // console.log(record)
        this.$refs.deviceInfoInfo.setDeviceInfoFormValues(record)
        this.deviceInfoInfo.visiable = true
      },
      handleDeviceInfoInfoClose() {
        this.deviceInfoInfo.visiable = false
        this.search()
      },

      editInfo(record) {
        if(record.auditStatus === '01' || record.auditStatus === '11' || record.auditStatus === '21'
          || record.auditStatus === '31' || record.auditStatus === '41') {
          this.$message.warning('申请待审批的数据不允许修改')
        } else {
          record.brandCode = record.brandCode + '-' + record.brandName
          record.modelCode = record.modelCode + '-' + record.modelName

          let effectiveDate = []
          effectiveDate[0]=record.startDate
          effectiveDate[1]=record.endDate
          record.effectiveDate = effectiveDate
          let leaseDate = []
          leaseDate[0]=record.leaseStartDate
          leaseDate[1]=record.leaseEndDate
          record.leaseDate = leaseDate
          // console.log(record)
          // setTimeout(() => {
          this.$refs.deviceInfoEdit.setDeviceInfoFormValues(record)
          // }, 1000);
          this.deviceInfoEdit.visiable = true
        }
      },

      handleDeviceInfoEditSuccess() {
        this.deviceInfoEdit.visiable = false
        this.$message.success('修改成功')
        this.search()
      },
      handleDeviceInfoEditClose() {
        this.deviceInfoEdit.visiable = false
        this.deviceInfoInfo.data = {}
        this.search()
      },

      search() {
        this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
        if (this.paginationInfo) {
          this.paginationInfo.current = this.pagination.defaultCurrent
          this.paginationInfo.pageSize = this.pagination.defaultPageSize
        }

        this.dataSource=[]
        let {sortedInfo, filteredInfo} = this
        let sortField, sortOrder
        // 获取当前列的排序和列的过滤规则
        if (sortedInfo) {
          sortField = sortedInfo.field
          sortOrder = sortedInfo.order
        }
        let params = {}
        params.instId = this.queryParams.instId
        params.deviceNo = this.queryParams.deviceNo
        params.brandCode = this.queryParams.brandCode
        params.modelCode = this.queryParams.modelCode

        this.fetch({
          sortField: sortField,
          sortOrder: sortOrder,
          ...params,
          ...filteredInfo
        })
      },
      reset() {
        // 取消选中
        this.selectedRowKeys  = []
        // 重置分页
        this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
        if (this.paginationInfo) {
          this.paginationInfo.current = this.pagination.defaultCurrent
          this.paginationInfo.pageSize = this.pagination.defaultPageSize
        }
        // 重置列排序规则
        this.sortedInfo = null
        // 重置查询参数
        this.queryParams = {}
        // // 清空时间选择
        // this.$refs.createTime.reset()
        this.fetch()
      },
      handleTableChange(pagination, filters, sorter) {
        this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
        if (this.paginationInfo) {
          this.paginationInfo.current = this.pagination.defaultCurrent
          this.paginationInfo.pageSize = this.pagination.defaultPageSize
        }

        // 将这三个参数赋值给Vue data，用于后续使用
        this.paginationInfo = pagination
        this.filteredInfo = filters
        this.sortedInfo = sorter

        this.fetch({
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...this.queryParams,
          ...filters
        })
      },
      fetch(params = {}) {
        this.loading = true
        if (this.paginationInfo) {
          // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
          this.$refs.TableInfo.pagination.current = this.paginationInfo.current
          this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
          params.pageSize = this.paginationInfo.pageSize
          params.pageNum = this.paginationInfo.current
        } else {
          // 如果分页信息为空，则设置为默认值
          params.pageSize = this.pagination.defaultPageSize
          params.pageNum = this.pagination.defaultCurrent
        }
        this.$get('deviceInfo', {
          ...params
        }).then((r) => {
          let data = r.data
          const pagination = {...this.pagination}
          pagination.total = data.total
          this.dataSource = data.rows
          this.pagination = pagination
          this.loading = false
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  @import "../../../../../../../static/less/Common";
</style>

